/*
 * Copyright © 2009 Gerald Isaac Schwarz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package driver;

import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import org.xml.sax.SAXException;

import base.UpgradeZone;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

public class GameLoader {
	private File file;
	private Document document;
	private ArrayList<base.Player> players;
	private ArrayList<base.Piece> types;
	private ArrayList<base.Board> boards;
	private base.Engine engine;
	private Driver driver;
	private base.Player currentPlayer;
	
	public GameLoader(File file) {
		this.file = file;
		
		if (!this.file.exists()) {
			throw new RuntimeException("Specified file doesn't exist.");
		}
		else if (this.file.isDirectory()) {
			throw new RuntimeException("Specified file is a directory.");
		}
		
		try {
			this.getDocument();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			this.loadGame();
		} catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void getDocument() throws IOException, SAXException, ParserConfigurationException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(true);
//		dbf.setNamespaceAware(true);
		dbf.setIgnoringElementContentWhitespace(true);
		this.document = dbf.newDocumentBuilder().parse(file);
		this.document.getDocumentElement().normalize();
	}
	
	private void loadTypes() {
		NodeList typeNodes = this.document.getElementsByTagName("type");
		this.types = new ArrayList<base.Piece>();
		
		for (int i = 0; i < typeNodes.getLength(); i++) {
			Element type = (Element) typeNodes.item(i);
			String name = this.getTextContent(type.getAttributes().getNamedItem("name"));
			
			String rule_type;
			
			if (type.hasAttribute("rule_type")) {
				rule_type = this.getTextContent(type.getAttributes().getNamedItem("rule_type"));
			}
			else {
				rule_type = null;
			}
			
			String representation = this.getTextContent(type.getAttributes().getNamedItem("representation"));
			NodeList moveNodes = type.getElementsByTagName("move");
			NodeList upgradeNodes = type.getElementsByTagName("upgrade");
			ArrayList<base.Move> moves = new ArrayList<base.Move>();
			ArrayList<String> upgrades= new ArrayList<String>();
			
			for (int h = 0; h < moveNodes.getLength(); h++) {
				Element move = (Element) moveNodes.item(h);
				int x = Integer.parseInt(this.getTextContent(move.getElementsByTagName("x").item(0)));
				int y = Integer.parseInt(this.getTextContent(move.getElementsByTagName("y").item(0)));
				int repetitions = Integer.parseInt(this.getTextContent(move.getElementsByTagName("repetitions").item(0)));
				boolean isMove = Boolean.parseBoolean(this.getTextContent(move.getElementsByTagName("is_move").item(0)));
				boolean isAttack = Boolean.parseBoolean(this.getTextContent(move.getElementsByTagName("is_attack").item(0)));
				
				moves.add(new base.Move(new Point(x, y), repetitions, isMove, isAttack));
			}
			
			for (int h = 0; h < upgradeNodes.getLength(); h++) {
				upgrades.add(this.getTextContent(upgradeNodes.item(h).getAttributes().getNamedItem("name")));
			}
			
			this.types.add(new base.Piece(name, rule_type, representation, moves, upgrades));
		}
	}
	
	private void loadPlayers() {
		NodeList players = this.document.getElementsByTagName("player");
		this.players = new ArrayList<base.Player>();
		
		for (int i = 0; i < players.getLength(); i++) {
			String id = this.getTextContent(players.item(i).getAttributes().getNamedItem("id"));
			int direction = Integer.parseInt(this.getTextContent(players.item(i).getAttributes().getNamedItem("direction")));
			String colorConstant = this.getTextContent(players.item(i).getAttributes().getNamedItem("color"));
			
			Color color;
			
			try {
				color = (Color) Color.class.getField(colorConstant).get(null);
			}
			catch (Exception e) {
				color = Color.BLACK;
			}
			
			this.players.add(new base.Player(id, color, direction));
		}
	}
	
	private void loadBoards() {
		NodeList boardNodes = this.document.getElementsByTagName("board");
		this.boards = new ArrayList<base.Board>();
		
		for (int i = 0; i < boardNodes.getLength(); i++) {
			int boardWidth = Integer.parseInt(this.getTextContent(boardNodes.item(i).getAttributes().getNamedItem("width")));
			int boardHeight = Integer.parseInt(this.getTextContent(boardNodes.item(i).getAttributes().getNamedItem("height")));
			
			this.boards.add(new base.Board(new Dimension(boardWidth, boardHeight)));
			
			NodeList upgrade_zoneNodes = ((Element) boardNodes.item(i)).getElementsByTagName("upgrade_zone");
			ArrayList<UpgradeZone> upgradeZones = new ArrayList<UpgradeZone>();
			
			for (int h = 0; h < upgrade_zoneNodes.getLength(); h++) {
				int x = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("x")));
				int y = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("y")));
				int zoneWidth = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("width")));
				int zoneHeight = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("height")));
				
				NodeList idNodes = ((Element) upgrade_zoneNodes.item(h)).getElementsByTagName("id");
				ArrayList<base.Player> players = new ArrayList<base.Player>();
				
				for (int q = 0; q < idNodes.getLength(); q++) {
					players.add(this.players.get(Integer.parseInt(this.getTextContent(idNodes.item(q)))));
				}
				
				upgradeZones.add(new UpgradeZone(new Rectangle(x, y, zoneWidth, zoneHeight), players));
			}
			
			this.boards.get(i).setUpgradeZones(upgradeZones);
			
			NodeList pieceNodes = ((Element) boardNodes.item(i)).getElementsByTagName("piece");
			
			for (int h = 0; h < pieceNodes.getLength(); h++) {
				String type = this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("type"));
				Integer id = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("player")));
				boolean is_alive = Boolean.parseBoolean(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("is_alive")));
				int x = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("x")));
				int y = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("y")));
				
				base.Piece upgrade = null;
				base.Player player = this.players.get(id);
				
				if (((Element) pieceNodes.item(h)).hasAttribute("upgrade")) {
					upgrade = this.getPieceByType(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("upgrade")));
				}
				
				base.Piece piece = this.getPieceByType(type);
				
				if (piece != null) {
					piece.setOwner(player);
					piece.setLocation(new Point(x, y));
					piece.setAlive(is_alive);
					
					if (upgrade != null) {
						piece.setUpgrade(upgrade);
					}
					
					this.boards.get(i).addPiece(piece);
				}
			}
		}
	}
	
	/**
	 * 
	 * @param type The type of the piece type we want to get an instance of.
	 * @return New instance of a piece from the piece templates.
	 */
	
	private base.Piece getPieceByType(String type) {
		for (base.Piece template : this.types) {
			if (template.getType().equals(type)) {
				return new base.Piece(template);
			}
		}
		
		return null;
	}
	
	private void loadGame() throws DOMException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		this.loadTypes();
		this.loadPlayers();
		this.loadCurrentPlayer();
		this.loadBoards();
		this.loadEngine();
		this.loadDriver();
	}
	
	private void loadCurrentPlayer() {
		int index = Integer.parseInt(this.getTextContent(this.document.getElementsByTagName("current_player").item(0)));
		
		this.currentPlayer = this.players.get(index);
	}
	
	private void loadEngine() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		String classname = this.getTextContent(this.document.getElementsByTagName("engine").item(0));
		
		this.engine = (base.Engine) GameLoader.class.getClassLoader().loadClass("engine." + classname).newInstance();
		this.engine.setBoard(this.boards.get(0));
		this.engine.setTypes(this.types);
		this.engine.setPlayers(this.players);
		this.engine.setCurrentPlayer(this.currentPlayer);
	}
	
	private void loadDriver() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		String classname = this.getTextContent(this.document.getElementsByTagName("driver").item(0));
		
		this.driver = (Driver) GameLoader.class.getClassLoader().loadClass("driver." + classname).newInstance();
		this.driver.setEngine(this.engine);
	}
	
	private String getTextContent(Node node) {
		return node.getTextContent().trim();
	}
	
	public Driver getDriver() {
		return this.driver;
	}
}
